<template>
	<view class="p-20 bb">
		<view class="box-card shadow-1">
			<image show-menu-by-longpress :src="imgUrl" class="w-100p" mode="widthFix"></image>
		</view>
		<view @click="saveAlbum" class="box-btn mt-50 mlr wfc shadow-1">
			<text>保存到相册</text>
		</view>
	</view>
</template>

<script>
	import {
		createQRCode
	} from '@/api/extend.js';
	export default {
		data() {
			return {
				imgUrl: ''
			}
		},
		onLoad() {
			this.getcreateQRCode();
		},
		methods: {
			getcreateQRCode() {
				let data = uni.getStorageSync('user_spread_code');
				if (data) {
					this.imgUrl = data
					return;
				}
				uni.showLoading({
					title:'生成中...'
				})
				createQRCode().then(res => {
					uni.hideLoading();
					if (res.status == 200) {
						this.imgUrl = res.data;
						uni.setStorageSync('user_spread_code', res.data)
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 4000
						})
					}

				})
			},
			saveAlbum() {

				uni.downloadFile({
					url: this.imgUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							// 下载成功后，保存图片到相册
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: () => {
									uni.showToast({
										title: '保存成功',
										icon: 'success'
									});
								},
								fail: (err) => {
									uni.showToast({
										title: '保存失败,请长按图片保存',
										icon: 'none',
										duration:4000
									});
								}
							});
						} else {
							uni.showToast({
								title: '保存失败,请长按图片保存',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '保存失败,请长按图片保存',
							icon: 'none'
						});
						
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.box-btn:active {
		opacity: .5;
	}

	.box-btn {
		color: white;
		text-align: center;
		background-color: #1BA135;
		width: 320rpx;
		height: 80rpx;
		border-radius: 100rpx;
		line-height: 80rpx;
		font-size: 32rpx;
		font-weight: bold;
	}

	.box-card {
		margin-top: 10vh;
		margin-left: auto;
		margin-right: auto;
		border-radius: 12rpx;
		width: 400rpx;
		height: 400rpx;
	}
</style>